package leetcode;

import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.PriorityQueue;

class Solution_347 {
    public int[] topKFrequent(int[] nums, int k) {
        //1.使用map对nums中的数字出现次数进行计数，
        //2.使用队列根据map中出现数据次数进行由大到小进行排序
        //3.循环结束后输出队列中前k个字符
        Map<Integer,Integer> counter = new HashMap<>();
        PriorityQueue<Map.Entry<Integer,Integer>> result = new PriorityQueue<>(new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> integerIntegerEntry, Map.Entry<Integer, Integer> t1) {
                return t1.getValue() - integerIntegerEntry.getValue();
            }
        });
        for (int num : nums) {
            if (counter.containsKey(num)) {
                int count = counter.get(num);
                counter.put(num,count + 1);
            }else {
                counter.put(num,1);
            }
        }
        result.addAll(counter.entrySet());
        int[] s = new int[k];
        for (int i = 0; i < k; i++) {
            s[i] = result.poll().getKey();
        }
        return s;
    }

    public static void main(String[] args) {
        for (int i : new Solution_347().topKFrequent(new int[]{1, 1, 1, 2, 2, 3}, 3)) {
            System.out.println(i + " ,");
        }
    }
}
